package server.core;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Vector;

import server.database.DbConnectionCreator;

import entity.TextInfo;
import entity.UserInfo;

/**
 * 
 * @author Bell
 * 
 */
public class ServerCore {
	/**
	 * 用户登录
	 * 
	 * @param name
	 *            每个用户唯一的用户名
	 * @param password
	 *            用户密码
	 * @return 一个UserInfo结构体（包含用户id，用户名，昵称，学校），如果用户不存在或密码错误，返回null
	 */
	public static UserInfo login(String name, String password) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();

			String sql = "select * from user_info where name = '" + name
					+ "' and password = '" + password + "';";
			System.out.println(sql);

			ResultSet rs = stmt.executeQuery(sql);
			UserInfo user = new UserInfo();
			if (rs.first()) {
				System.out.println("=================user "
						+ rs.getString("name") + " log in================");
				user.setUID(rs.getLong("UID"));
				user.setName(rs.getString("name"));
				user.setNickname(rs.getString("nickname"));
				user.setSchool(rs.getString("school"));
				return user;
			}
		} catch (Exception e) {
			System.out
					.println("####################error login######################");
		}
		return null;
	}

	/**
	 * 添加新用户
	 * 
	 * @param user
	 *            用户信息类（用户id、是否是管理员无用）
	 * @return 是否添加成功
	 */
	public static boolean addUser(UserInfo user) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();

			String sql = "insert into user_info(name, password, isAdmin, nickname, school) values('"
					+ user.getName()
					+ "', '"
					+ user.getPassword()
					+ "', "
					+ user.getIsAdmin()
					+ ", '"
					+ user.getNickname()
					+ "', '"
					+ user.getSchool() + "');";
			System.out.println(sql);

			int rs = stmt.executeUpdate(sql);
			if (rs == 1) {
				System.out.println("================user " + user.getName()
						+ " added=============");
				return true;
			}
		} catch (Exception e) {
			System.out
					.println("################error add user####################");
		}
		return false;
	}

	/**
	 * 添加好友
	 * 
	 * @param user1
	 *            第一个用户的id
	 * @param user_name
	 *            第二个用户的用户名
	 * @return boolean是否添加成功
	 */
	public static boolean addFriend(long user1, long user2) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();

			// 插入（user1，user2）
			String sql = "insert into user_relation values(" + user1 + ", "
					+ user2 + ");";
			System.out.println(sql);

			int rs = stmt.executeUpdate(sql);
			if (rs == 1) {
				System.out.println("===================" + user1 + " and "
						+ user2 + " become friends=================");

				// 插入（user2，user1）
				sql = "insert into user_relation values(" + user2 + ", "
						+ user1 + ");";
				System.out.println(sql);

				rs = stmt.executeUpdate(sql);
				if (rs == 1) {
					System.out.println("=================" + user2 + " and "
							+ user1 + " become friends==================");
					return true;
				}
			}

		} catch (Exception e) {
			System.out
					.println("###############error add friends#################");
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查找用户
	 * 
	 * @param user
	 *            发起查找者的id
	 * @param nickname
	 *            要查找的人的昵称
	 * @return 一个vector，里面存了所有昵称为name的人的信息（用户id，用户昵称，学校，用户名），用户名域为user
	 *         name的人为其好友
	 */
	public static Vector<UserInfo> findUser(Long user, String nickname) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();
			Vector<UserInfo> userlist = new Vector<UserInfo>();

			// 获取user的用户名
			String sql = "select name from user_info where UID = " + user + ";";
			ResultSet rs = stmt.executeQuery(sql);
			if (rs.first()) {
				String username = rs.getString("name");
				// System.out.println(username);

				sql = "SELECT user_info.uid, '"
						+ username
						+ "', user_info.nickname, user_info.school "
						+ "FROM user_info, user_relation WHERE user_relation.user1 = "
						+ user
						+ " and user_relation.user2 = user_info.uid and user_info.nickname = '"
						+ nickname
						+ "' UNION SELECT user_info.uid, user_info.name, user_info.nickname, user_info.school "
						+ "FROM user_info, user_relation WHERE user_info.nickname = '"
						+ nickname
						+ "' and ("
						+ user
						+ ", user_info.uid) NOT IN (select * from user_relation);";
				System.out.println(sql);
				rs = stmt.executeQuery(sql);
				while (rs.next()) {
					UserInfo tmp = new UserInfo();
					tmp.setName(rs.getString(2));
					tmp.setUID(rs.getLong("UID"));
					tmp.setNickname(rs.getString("nickname"));
					tmp.setSchool(rs.getString("school"));
					userlist.addElement(tmp);
				}
				System.out.println("===================" + username
						+ " is finding users====================");

				/*
				 * //好友中昵称为nickname的人 sql =
				 * "select * from user_info, user_relation where nickname = '" +
				 * nickname +
				 * "' and user_relation.user1 = user_info.UID and user_relation.user2 = "
				 * + user + ";"; //System.out.println(sql);
				 * 
				 * rs = stmt.executeQuery(sql); while(rs.next()) { UserInfo tmp
				 * = new UserInfo();
				 * tmp.setName(username);//name为发起者的用户名，表示该用户是发起者的好友
				 * tmp.setUID(rs.getLong("UID"));
				 * tmp.setNickname(rs.getString("nickname"));
				 * tmp.setSchool(rs.getString("school"));
				 * userlist.addElement(tmp); }
				 * 
				 * //不认识的人中昵称为nickname的人 sql =
				 * "select * from user_info where nickname = '" + nickname +
				 * "' and UID <> " + user + ";"; //System.out.println(sql);
				 * 
				 * rs = stmt.executeQuery(sql); while(rs.next()) {
				 * //查找在userlist中是否已经存在该用户id boolean flag = true; for(int i = 0;
				 * i < userlist.size(); i++) { if(userlist.get(i).getUID() ==
				 * rs.getLong("UID")) { flag = false; break; } } if(flag) {
				 * UserInfo usr = new UserInfo();
				 * usr.setName(rs.getString("name"));
				 * usr.setUID(rs.getLong("UID"));
				 * usr.setNickname(rs.getString("nickname"));
				 * usr.setSchool(rs.getString("school")); userlist.add(usr); } }
				 */
				return userlist;
			} else
				System.out
						.println("###################user not exist!###################");

		} catch (Exception e) {
			System.out
					.println("####################error find user################");
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 添加新鲜事
	 * 
	 * @param textinfo
	 *            新鲜事信息
	 * @return 是否添加成功
	 */
	public static boolean publishNewsfeed(TextInfo textinfo) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();
			textinfo.setDatetime(new Timestamp(System.currentTimeMillis()));// 获取当前时间

			String sql = "insert into text_base(content, author, time, type) values ('"
					+ textinfo.getText()
					+ "', "
					+ textinfo.getUID()
					+ ", '"
					+ textinfo.getDatetime()
					+ "', "
					+ textinfo.getType()
					+ ");";
			System.out.println(sql);

			int res = stmt.executeUpdate(sql);
			if (res == 1) {
				System.out
						.println("==============newsfeed published================");
				return true;
			}
		} catch (Exception e) {
			System.out
					.println("######################error publish newsfeed##################");
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 查看新鲜事
	 * 
	 * @param uid
	 *            用户id
	 * @return 所有该用户好友的新鲜事列表
	 */
	public static Vector<TextInfo> viewNewsfeed(long uid) {
		try {
			Connection conn = DbConnectionCreator.getConnection();
			Statement stmt = conn.createStatement();
			Vector<TextInfo> textlist = new Vector<TextInfo>();

			String sql = "select distinct user_info.nickname, text_base.TID, text_base.author, "
					+ "text_base.time, text_base.type, text_base.content from text_base, user_info, "
					+ "user_relation where (user_relation.user1 = "
					+ uid
					+ " and user_relation.user2 = user_info.UID "
					+ "and user_relation.user2 = text_base.author) or (text_base.author = "
					+ uid
					+ " and user_info.UID = "
					+ uid
					+ ") order by text_base.time desc;";
			System.out.println(sql);
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				TextInfo ti = new TextInfo();
				ti.setName(rs.getString("nickname"));
				ti.setTID(rs.getLong("TID"));
				ti.setText(rs.getString("content"));
				ti.setUID(rs.getLong("author"));
				ti.setDatetime(rs.getTimestamp("time"));
				ti.setType(rs.getInt("type"));
				textlist.add(ti);
			}
			System.out
					.println("==================viewing newsfeed==================");
			return textlist;

		} catch (Exception e) {
			System.out
					.println("######################error view newsfeed###################");
			e.printStackTrace();
		}
		return null;
	}
}
